package com.seo.service.lightpay.impl;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.seo.mapper.lightpay.LightPayMapper;
import com.seo.pojo.lightpay.LightPayCashier;
import com.seo.pojo.transaction.TransactionFlow;
import com.seo.service.lightpay.sdk.LightPayProxyService;
import com.seo.service.lightpay.sdk.LightPayService;
import com.seo.service.transaction.sdk.TransactionService;
import com.seo.pojo.ReturnBody;
import com.seo.utils.CustomUtil;
import com.seo.utils.DateUtil;
import com.seo.utils.WebUtil;

import lombok.extern.slf4j.Slf4j;

@Slf4j
@Service("lightPayService")
public class LightPayServiceImpl implements LightPayService {

	public static ExecutorService OrderThreadPool = Executors.newFixedThreadPool(3);

	@Autowired
	private TransactionService transactionService;

	@Autowired
	private LightPayMapper lightPayMapper;
	
	private Map<String, LightPayProxyService> proxys = new HashMap<>();

	public void put(String type, LightPayProxyService obj) {
		proxys.put(type, obj);
	}

	public ReturnBody getCheckParams(String tradeId, LightPayCashier lpc) {
		ReturnBody body = ReturnBody.init();
		int userId = lpc.getUserId();
		if (userId <= 0) {
			log.error("[{}]-【用户不存在】", tradeId);
			return body.error("用户不存在");
		}

		if (StringUtils.isEmpty(lpc.getPayMode()) || !LightPayCashier.PayMode.isExists(lpc.getPayMode())
				|| !proxys.containsKey(lpc.getPayMode())) {
			log.error("[{}]-【支付方式不存在】", tradeId);
			return body.error("请选择支付方式");
		}

		if (StringUtils.isEmpty(lpc.getPayType())) {
			log.error("[{}]-【支付类型不存在】", tradeId);
			return body.error("请选择支付类型");
		}

		LightPayProxyService service = get(lpc.getPayMode());

		body.run(service.getCheckParams(tradeId, lpc));

		if (!body.isSuccess()) {
			return body.clean();
		}
		return body.success();
	}

	public ReturnBody getCheckLightPayCashier(String tradeId, LightPayCashier lpc) {
		ReturnBody body = ReturnBody.init();
		if (StringUtils.isEmpty(lpc.getTransactionCode())) {
			log.error("[{}]-【交易不存在】", tradeId);
			return body.error("交易不存在");
		}

		TransactionFlow tf = transactionService.getTransactionFlow(lpc.getTransactionCode());

		if (tf == null) {
			log.error("[{}]-【交易订单[{}]不存在】", tradeId, lpc.getTransactionCode());
			return body.error("交易订单不存在");
		}

		if (!TransactionFlow.State.no.equals(tf.getState())) {
			if (TransactionFlow.State.finish.equals(tf.getState())) {
				log.error("[{}]-【交易订单[{}]已支付】", tradeId, lpc.getTransactionCode());
				return body.error("交易订单已支付");
			} else {
				log.error("[{}]-【交易订单[{}]已取消】", tradeId);
				return body.error("交易订单已取消");
			}
		}

		// 验证金额
		if (tf.getPayAmount().compareTo(BigDecimal.ZERO) <= 0) {
			log.error("[{}]-【支付金额有误】", tradeId);
			return body.error("支付金额有误");
		}
		lpc.setAmount(tf.getPayAmount());
		lpc.setIp(WebUtil.getIpAddr());
		List<LightPayCashier> lpcnewList = lightPayMapper.getLightpayCashierByTCode(tf.getCode(), lpc.getPayType(),
				lpc.getPayMode());
		LightPayCashier lpcnew = null;
		if (lpcnewList != null && lpcnewList.size() == 1) {
			lpcnew = lpcnewList.get(0);
		}

		if (lpcnew != null && !TransactionFlow.State.no.equals(lpcnew.getState())) {
			log.error("[{}]-【请不要重复提交】", tradeId);
			return body.error("请不要重复提交");
		}
		String curTime = DateUtil.getTime();
		if (lpcnew != null) {
			lpc.setId(lpcnew.getId());
			lpc.setRemark(lpcnew.getRemark());
			lpc.setCode(lpcnew.getCode());
			lpc.setVersion(lpcnew.getVersion());
		} else {
			// 插入收银记录
			lpc.setRemark(tf.getRemark());
			lpc.setCreateTime(curTime);
			lpc.setParentUserId(tf.getParentUserId());
			lpc.setState(LightPayCashier.State.no.getValue());
			lightPayMapper.saveLightpayCashier(lpc);
			lpc.setCode(CustomUtil.orderCode(3, lpc.getId(), lpc.getUserId()));
			int num = lightPayMapper.updateLightpayCashierCode(lpc);
			if (num != 1) {
				log.error("[{}]-【收银记录保存失败】", tradeId);
				return body.rollback("请重新结算");
			}
		}
		return body.success();
	}

	@Override
	public ReturnBody saveLightPayCashier(String tradeId, LightPayCashier lpc) {
		LightPayProxyService service = get(lpc.getPayMode());

		ReturnBody body = ReturnBody.init();

		// 校验账单、收银记录
		log.info("[{}]-【校验账单、收银记录】", tradeId);
		body.run(getCheckLightPayCashier(tradeId, lpc));
		if (!body.isSuccess()) {
			return body;
		}

		return service.saveLightPayCashier(tradeId, lpc);

	}


	@Override
	public ReturnBody getLightpayCashierByCode(String tradeId, String code) {
		ReturnBody body = ReturnBody.init();
		LightPayCashier lpc = lightPayMapper.getLightpayCashierByCode(code);
		if (lpc == null) {
			log.error("[{}]-【收银[{}]不存在】", tradeId, code);
			return body.error("收银不存在");
		}
		TransactionFlow tf = transactionService.getTransactionFlow(lpc.getTransactionCode());
		if (tf == null) {
			log.error("[{}]-【交易流水[{}]不存在】", tradeId, lpc.getTransactionCode());
			return body.error("交易流水不存在");
		}

		body.put("tf", tf);

		return body.success();
	}

	public LightPayProxyService get(String payMode) {
		return proxys.get(payMode);
	}
}
